﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Ultimus.WFServer;
using H2.NET.Common;
using H2.NET.Web.Workflow.DwzCode;

namespace H2.NET.Web.Workflow
{
    public partial class Monitor : BasePage
    {
        [SessionType]
        public clsCommon clsCmm = new clsCommon();
        private DataTable dt = new DataTable();
        public string str_monitor_2_url = "";
        public string str_incident_summary = "";

        #region 事件 页面 加载
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                //参数接收
                string strType = Request.QueryString["type"];
                string strTaskID = Request.QueryString["TaskID"];

                //第一次加载页面时初始化
                if (!Page.IsPostBack)
                {
                    bool Flg = false;
                    Task tskTemp = new Task();

                    //数据合法性验证
                    if (strType == null || strType.Trim() == "")
                    {
                        strType = "-1";
                    }

                    if (strTaskID == null || strTaskID.Trim() == "")
                    {
                        TaskDB.Log("", false, "调用 monitor.aspx 页面 Page_Load 事件出错：TaskID 传入不正确！");
                        return;
                    }

                    if (strType != "-1")
                    {
                        //根据业务类型及业务表的 TaskId 来间接取得对应流程 Ultimus TaskId
                        strTaskID = get_ultimus_taskid_by_type_taskid(strType, strTaskID);

                        //如果为空，则退出
                        if (strTaskID == "")
                        {
                            TaskDB.Log("", false, "调用 monitor.aspx 页面 Page_Load 事件出错：Type、TaskID 传入不正确！");
                            return;
                        }
                    }

                    //根据 TaskID 去取得表单对应的 url 地址
                    Flg = tskTemp.InitializeFromTaskId(strTaskID);

                    //如果返回为 true 时
                    if (Flg)
                    {
                        ViewState["ProcessName"] = tskTemp.strProcessName;
                        ViewState["IncidentNo"] = tskTemp.nIncidentNo.ToString();
                        ViewState["ProcessVersion"] = tskTemp.nProcessVersion.ToString();

                        //实例摘要
                        if (tskTemp.strSummary.Trim() != "")
                        {
                            str_incident_summary = " - " + tskTemp.strSummary;
                        }
                        else
                        {
                            str_incident_summary = "";
                        }
                    }
                    else
                    {
                        TaskDB.Log("", false, "调用 monitor.aspx 页面 Page_Load 事件出错：TaskID: " + strTaskID + " 传入不正确，无法取得对应的任务信息！");
                        return;
                    }

                    //查询并对列表进行数据绑定
                    load_gv_monitor_list();
                }

                //图像监控 url 地址
                str_monitor_2_url = "FlowChart.ashx?TaskID=" + strTaskID;
            }
            catch (Exception ee)
            {
                TaskDB.Log("", false, "调用 monitor.aspx 页面 Page_Load 事件出错：" + ee.Message);
            }
        }
        #endregion

        #region 方法 获取收件箱列表
        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public DataTable get_all_monitor()
        {
            try
            {
                string strSQL = "";

                string strProcessName = ViewState["ProcessName"].ToString();
                string strIncidentNo = ViewState["IncidentNo"].ToString();
                string strProcessVersion = ViewState["ProcessVersion"].ToString();

                //数据合法性检查
                if (strProcessName == null || strProcessName.Trim() == "")
                {
                    strProcessName = "";
                }

                if (strIncidentNo == null || strIncidentNo.Trim() == "")
                {
                    strIncidentNo = "-1";
                }

                if (strProcessVersion == null || strProcessVersion.Trim() == "")
                {
                    strProcessVersion = "1";
                }

                //查找收件箱列表
                strSQL = "SELECT DISTINCT b.*,'' AS taskuser2,'' AS assignedtouser2, '' AS img_status,'' AS starttime2,'' AS endtime2, c.fullname AS taskuser_name, d.fullname AS assignedtouser_name " +
                         " FROM(" +
                         "     SELECT steplabel, taskid, taskuser, assignedtouser, status,substatus, starttime, endtime, stepid FROM tasks WHERE processname = '" + strProcessName + "' AND incident = " + strIncidentNo + " AND status > 1 " +
                         "     UNION ALL " +
                         "     SELECT steplabel, taskid, taskuser, assignedtouser, status, substatus, starttime, endtime, stepid FROM tasks WHERE processname = '" + strProcessName + "' AND incident = " + strIncidentNo + " AND status = 1 AND steplabel NOT IN (SELECT steplabel FROM tasks WHERE processname = '" + strProcessName + "' AND incident = " + strIncidentNo + " AND status > 1)" +
                         " ) b " +
                         " LEFT JOIN jobs c ON b.taskuser = c.name " +
                         " LEFT JOIN jobs d ON b.assignedtouser = d.name " +
                         " where b.stepid IN (" +
                         "     SELECT stepid FROM processsteps WHERE processname = '" + strProcessName + "' AND processversion = " + strProcessVersion + " AND steptype IN (2, 4)" +
                         " ) ORDER BY b.starttime";

                clsCmm.clsDB.Storage("bpmDB");
                dt = clsCmm.clsDB.Query(strSQL);
                //TaskDB.Log("", true, "调用 monitor.aspx 页面 get_all_monitor 方法 SQL：" + strSQL);

                //在没有结果返回的情况，返回一空白行
                if (dt.Rows.Count == 0)
                {
                    DataRow dr = dt.NewRow();
                    dt.Rows.Add(dr);
                }

                return dt;
            }
            catch (Exception ee)
            {
                TaskDB.Log("", false, "调用 monitor.aspx 页面 get_all_monitor 方法出错：" + ee.Message);
                return null;
            }
        }
        #endregion

        #region 方法 查询并对列表进行数据绑定
        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public void load_gv_monitor_list()
        {
            try
            {
                //加载列表
                dt = get_all_monitor();

                //设置状态列的图片
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    #region 如果没有姓名信息，则显示用户名

                    if (dt.Rows[i]["taskuser_name"] == DBNull.Value || dt.Rows[i]["taskuser_name"].ToString().Trim() == "")
                    {
                        dt.Rows[i]["taskuser_name"] = dt.Rows[i]["taskuser"].ToString();
                    }

                    if (dt.Rows[i]["assignedtouser_name"] == DBNull.Value || dt.Rows[i]["assignedtouser_name"].ToString().Trim() == "")
                    {
                        dt.Rows[i]["assignedtouser_name"] = dt.Rows[i]["assignedtouser"].ToString();
                    }

                    #endregion

                    if (!(dt.Rows[i]["starttime"] == DBNull.Value || dt.Rows[i]["starttime"].ToString().Trim() == ""))
                    {
                        dt.Rows[i]["starttime2"] = System.Convert.ToDateTime(dt.Rows[i]["starttime"]).ToString("yyyy-MM-dd HH:mm");
                    }

                    #region 如果任务是 Actived 的情况

                    //如果任务是 Actived 的情况
                    if (dt.Rows[i]["status"].ToString().Trim() == "1")
                    {
                        dt.Rows[i]["endtime"] = DBNull.Value;
                        switch (dt.Rows[i]["substatus"].ToString().Trim())
                        {
                            case "0":
                            case "1":
                                dt.Rows[i]["img_status"] = "frm_inbox_late.gif";
                                break;

                            case "2":
                                dt.Rows[i]["img_status"] = "frm_inbox_overdue.gif";
                                break;

                            case "3":
                                dt.Rows[i]["img_status"] = "frm_inbox_urgent.gif";
                                break;

                            case "4":
                                dt.Rows[i]["img_status"] = "frm_inbox_reassigned.gif";
                                break;

                            case "7":
                                dt.Rows[i]["img_status"] = "frm_inbox_urgent.gif";
                                break;

                            case "8":
                                dt.Rows[i]["img_status"] = "frm_inbox_late.gif";
                                break;

                            case "16":
                                dt.Rows[i]["img_status"] = "frm_inbox_returned.gif";
                                break;

                            case "32":
                                dt.Rows[i]["img_status"] = "frm_inbox_resubmitted.gif";
                                break;

                            default:
                                dt.Rows[i]["img_status"] = "frm_initiate_blank.gif";
                                break;
                        }
                    }
                    //步骤取消的情况
                    else if (dt.Rows[i]["status"].ToString().Trim() == "7")
                    {
                        dt.Rows[i]["img_status"] = "frm_inbox_aborted.gif";
                    }
                    #endregion

                    #region 如果任务是 Completed 的情况

                    //如果任务是 Completed 的情况
                    if (dt.Rows[i]["status"].ToString().Trim() == "3")
                    {
                        dt.Rows[i]["img_status"] = "frm_complete_complete.gif";
                        dt.Rows[i]["endtime2"] =string.Format("{0:yyyy-MM-dd HH:mm}",dt.Rows[i]["endtime"].ToString());
                    }

                    #endregion

                    #region 如果任务是 Returned 的情况

                    //如果任务是 Returned 的情况
                    if (dt.Rows[i]["status"].ToString().Trim() == "4")
                    {
                        dt.Rows[i]["img_status"] = "frm_complete_pending.gif";
                        dt.Rows[i]["endtime2"] = string.Format("{0:yyyy-MM-dd HH:mm}",dt.Rows[i]["endtime"].ToString());
                    }

                    #endregion

                    #region 去除账号前面的域名

                    //去除账号前面的域名
                    if (-1 != dt.Rows[i]["taskuser"].ToString().IndexOf('/'))
                    {
                        dt.Rows[i]["taskuser2"] = dt.Rows[i]["taskuser"].ToString().Substring(dt.Rows[i]["taskuser"].ToString().IndexOf('/') + 1);
                    }
                    else
                    {
                        dt.Rows[i]["taskuser2"] = dt.Rows[i]["taskuser"].ToString();
                    }

                    //去除账号前面的域名
                    if (-1 != dt.Rows[i]["assignedtouser"].ToString().IndexOf('/'))
                    {
                        dt.Rows[i]["assignedtouser2"] = dt.Rows[i]["assignedtouser"].ToString().Substring(dt.Rows[i]["assignedtouser"].ToString().IndexOf('/') + 1);
                    }
                    else
                    {
                        dt.Rows[i]["assignedtouser2"] = dt.Rows[i]["assignedtouser"].ToString();
                    }
                    #endregion
                }

                //第一次没有排序字段的情况
                if (ViewState["OrderBy"] == null)
                {
                    dt.DefaultView.Sort = "starttime ASC";
                }
                else
                {
                    dt.DefaultView.Sort = ViewState["OrderBy"] + " " + ViewState["Order"];
                }

                rpt_monitor.DataSource = dt;
                rpt_monitor.DataBind();
            }
            catch (Exception ee)
            {
                TaskDB.Log("", false, "调用 monitor.aspx 页面 load_gv_monitor_list方法出错：" + ee.Message);
            }
        }
        #endregion

        #region 方法 根据 业务类型以及业务taskid 来取得 Ultimus 对应 TaskId
        /// <summary>
        /// 
        /// </summary>
        public string get_ultimus_taskid_by_type_taskid(string strType, string strTaskId)
        {
            try
            {
                string strSQL = "";
                string strProcess = "";
                string strIncident = "";

                #region 根据传入的类型来取得 “根据业务表 TaskId 来取得对应 Ultimus 表中的 Process & Incident 的 SQL”
                //主查询 SQL
                strSQL = "select get_process_incident_sql from t_process_config where id='" + strType + "'";
                clsCmm.clsDB.Storage("oleDB");
                dt = clsCmm.clsDB.Query(strSQL);

                //如果存在返回值的情况
                if (dt.Rows.Count > 0)
                {
                    strSQL = dt.Rows[0]["get_process_incident_sql"].ToString().Trim().Replace("{0}", strTaskId);
                }
                else
                {
                    TaskDB.Log("", false, "调用 monitor.aspx 页面 get_ultimus_taskid_by_type_taskid 事件出错：Type 传入不正确！");
                    return "";
                }
                #endregion

                #region 根据业务表 TaskId 来取得对应 Ultimus 表中的 Process & Incident
                //查询对应的 Process & Incident
                clsCmm.clsDB.Storage("oleDB");
                dt = clsCmm.clsDB.Query(strSQL);

                //如果存在返回值的情况
                if (dt.Rows.Count > 0)
                {
                    strProcess = dt.Rows[0]["Process"].ToString().Trim();
                    strIncident = dt.Rows[0]["Incident"].ToString().Trim();
                }
                else
                {
                    TaskDB.Log("", false, "调用 monitor.aspx 页面 get_ultimus_taskid_by_type_taskid 事件出错：根据 Type、TaskId 找不到对应的 Process、Incident！");
                    return "";
                }
                #endregion

                #region 根据流程名及实例号从 Ultimus 表中取得对应的 TaskID
                //主查询SQL
                strSQL = "select a.taskid";
                strSQL += "  from tasks a, processsteps b";
                strSQL += " where a.processname = '" + strProcess + "'";
                strSQL += "   and a.incident = " + strIncident + "";
                strSQL += "   and a.status = 3";
                strSQL += "   and b.steptype in (4,2)";
                strSQL += "   and a.processversion = b.processversion ";
                strSQL += "   and a.stepid = b.stepid";
                strSQL += "   and a.processname = b.processname order by a.endtime desc";

                TaskDB.Log("", true, "调用 monitor.aspx 页面 get_ultimus_taskid_by_type_taskid 方法SQL：" + strSQL);

                //从数据中查询
                clsCmm.clsDB.Storage("bpmDB");
                dt = clsCmm.clsDB.Query(strSQL);
                if (dt.Rows.Count > 0)
                {
                    //根据 Ultimus 的 TaskId 来取得对应的 FormUrl
                    return dt.Rows[0]["taskid"].ToString().Trim();
                }
                #endregion

                return "";
            }
            catch (Exception ee)
            {
                TaskDB.Log("", false, "调用 monitor.aspx 页面 get_ultimus_taskid_by_type_taskid 方法出错：" + ee.Message);
                return "";
            }

        }
        #endregion
    }
}
